package tjcu.archives.controller;


import com.github.pagehelper.PageInfo;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import tjcu.archives.entity.Menu;
import tjcu.archives.entity.User;
import tjcu.archives.service.MenuService;
import tjcu.archives.vo.*;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.List;

@Controller
@RequestMapping("/sel")
public class MenuController extends BaseVO {
    private Logger log = LoggerFactory.getLogger(MenuController.class);
    @Autowired
    private MenuService menuService;

    @RequestMapping("userRegister")
    public R UserRegister(String loginname, String password, String pwd) {
        menuService.register(loginname,password,pwd);
        return R.ok("注册成功");
    }

    //跳转到登陆页面
    @RequestMapping("toLogin")
    public String toLogin() {
        return "view/login";
    }

    /**
     * 登陆   shiro登陆
     */


    @RequestMapping("login")
    public String login(Model model, HttpServletRequest request, String loginname, String pwd) {
        //第一步：建立subject
        Subject subject = SecurityUtils.getSubject();
        //第二步：封装token  凭证
        UsernamePasswordToken token = new UsernamePasswordToken(loginname, pwd);

        //第三步：登陆
        try {
            //3. 执行认证
            subject.login(new UsernamePasswordToken(loginname, pwd));
            User users = menuService.loginname(loginname);
            //把user放进session
            request.getSession().setAttribute("user", users);
            model.addAttribute("loginname", users.getLoginName());
            model.addAttribute("id", users.getUserid());
            System.out.println(request.getSession());
            //把yonghu放进session
            request.getSession().setAttribute("yonghu", users.getLoginName());
            /***
             * 跳转首页
             */
            return "view/index";
        } catch (UnknownAccountException e) {
            //用户为空或不存在
            model.addAttribute("msg", "不存在这样的用户!");
            return "view/login";
        } catch (IncorrectCredentialsException e) {
            model.addAttribute("msg", "密码输入不对!");
            return "view/login";
        }
    }

    /***
     * 加载首页左边导航栏
     */
    @RequestMapping("toTreeLoad")
    @ResponseBody
    public List<TreeNodeVO> toTreeLoad(HttpServletRequest request) {
        //获取用户登陆id根据不同的用户有不同菜单
        User user = (User) request.getSession().getAttribute("user");
        ///获取用户登陆id根据不同的用户有不同菜单
        List<Menu> list = menuService.queryMenuByUid(user.getUserid());
        //创建list集合
        //把list放入nodes
        List<TreeNodeVO> nodes = new ArrayList<>();
        if (user.getUserid() != null) {
            for (Menu menus : list) {
                if (menus.getPid() == 0 || menus.getPid() == 1) {
                    TreeNodeVO vo = new TreeNodeVO();
                    BeanUtils.copyProperties(menus, vo);
                    nodes.add(vo);
                }
            }
        } else {
            for (Menu menus : list) {
                TreeNodeVO vo = new TreeNodeVO();
                BeanUtils.copyProperties(menus, vo);
                nodes.add(vo);
            }
        }


        //组装菜单
        List<TreeNodeVO> treeNodeVOS = new ArrayList<>();
        //n1.getPid() == 1 为父级菜单
        for (
                TreeNodeVO n1 : nodes) {
            if (n1.getPid() == 1) {
                treeNodeVOS.add(n1);
            }
            //将n2放入n1的子级中   id为子级
            for (TreeNodeVO n2 : nodes) {
                if (n2.getPid() == n1.getId()) {
                    n1.getChildren().add(n2);
                }
            }
        }
        return treeNodeVOS;
    }

    /**
     * 加载菜单管理左边的菜单树
     */
    @RequestMapping("loadMenuMangerLeftTreeJson")
    @ResponseBody
    public DataGridViewVO loadMenuMangerLeftTreeJson(Menu menu) {
        //查询所有菜单那
        List<Menu> list = menuService.queryMenuAllList(menu);
        //将查询的菜单循环放入TreeNode
        List<TreeNodeVO> nodes = new ArrayList<>();
        for (Menu menus : list) {
            Integer id = menus.getId();
            Integer pid = menus.getPid();
            String title = menus.getTitle();
            String icon = menus.getIcon();
            String href = menus.getHref();
            Boolean spread = menus.getSpread() == true;
            String target = menus.getTarget();
            nodes.add(new TreeNodeVO(id, pid, title, icon, href, spread, target));
        }
        return new DataGridViewVO(nodes);
    }

    /**
     * 查询所有菜单MenuRight
     */

    @RequestMapping("queryMenuAllList")
    @ResponseBody
    public R queryMenuAllList(String title,
                              @RequestParam(defaultValue = "1") Integer page,
                              @RequestParam(defaultValue = "10") Integer limit) {
        //1. 调用Service查询
        PageInfo<Menu> pageInfo = menuService.findByTitle(title, page, limit);

        //2. 封装数据
        long count = pageInfo.getTotal();
        List<SysMenuVO> data = new ArrayList<>();
        for (Menu sysMenu : pageInfo.getList()) {
            SysMenuVO vo = new SysMenuVO();
            BeanUtils.copyProperties(sysMenu, vo);
            data.add(vo);
        }

        //3. 返回
        return R.ok(count, data);
    }

    /**
     * 添加菜单
     */
    @RequestMapping("addMenu")
    @ResponseBody
    public String addMenu(Menu menu) {
        int i = menuService.addMenu(menu);
        if (i == 1) {
            return "添加成功";
        } else {
            return "添加失败";
        }
    }

    /***
     * 检查菜单
     * */
    @RequestMapping("checkMenuHasChildren")
    @ResponseBody
    public String checkMenuHasChildren(Integer id) {
        int pid_num = menuService.checkMenuHasChildren(id);
        if (pid_num <= 0) {
            return "1";
        } else {
            return "0";
        }

    }

    /**
     * 删除菜单
     */
    @RequestMapping("deleteMenu")
    @ResponseBody
    public String deleteMenu(Integer id) {
        int pid_num = menuService.deleteMenu(id);
        return "true";
    }

    /**
     * 修改菜单
     */
    @RequestMapping("updateMenu")
    @ResponseBody
    public Object updateMenu(Menu menu) {
        menuService.updateMenu(menu);
        return "修改成功";
    }
}
